import { getFsAppId, getFsAuth } from "@/api/auth";

// 封装飞书登录相关逻辑
export interface FeiShuAuthResult {
  code: string;
}

export interface FeiShuUserInfo {
  avatar_thumb: string;
  name: string;
  en_name: string;
}

declare interface Tt {
  requestAccess: (params: {
    scopeList: string[];
    appID: string;
    success?: (res: any) => void;
    fail?: (err: any) => void;
  }) => void;
}

declare global {
  interface Window {
    tt: Tt;
  }
}

/**
 * 获取飞书AppID
 */
export const fetchFeiShuAppId = async (): Promise<string> => {
  const appRes = await getFsAppId();
  if (appRes.code !== 0) {
    return;
    // throw new Error("飞书应用初始化失败");
  }
  return appRes.data;
};

/**
 * 请求用户授权
 * @param appId - 飞书AppID
 */
export const requestFeiShuAuthorization = async (
  appId: string
): Promise<FeiShuAuthResult> => {
  return new Promise((resolve, reject) => {
    window.tt.requestAccess({
      scopeList: [],
      appID: appId,
      success: resolve,
      fail: reject
    });
  });
};

/**
 * 处理后端认证
 * @param authCode - 授权码
 */
export const processBackendAuthentication = async (
  authCode: string
): Promise<FeiShuUserInfo> => {
  const authResult = await getFsAuth({ code: authCode });
  if (authResult.code !== 0) {
    throw new Error(authResult.message || "飞书登录失败");
  }
  return authResult.data;
};
